package com.qf.controller;

import com.qf.constant.CartConstant;
import com.qf.dto.ResultBean;
import com.qf.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author NingZhongYi
 * @Date 2020-03-11
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    // 添加购物车
    @RequestMapping("addCart/{productId}/{count}")
    @ResponseBody
    public ResultBean addCart(@CookieValue(name = CartConstant.REDIS_CART,required = false) String uuid, @PathVariable Long productId, @PathVariable Integer count, HttpServletResponse response){
      // 1 先判断是否有购物车 如果没有购物车则先创建购物车
       if (uuid==null||"".equals(uuid)){
           // 在浏览器端的cookie中没有购物车的UUID  说明没有购物车 先创建购物车
           uuid= UUID.randomUUID().toString();
           // 将UUID 存入到本地浏览器的cookie中
           Cookie cookie=new Cookie(CartConstant.REDIS_CART,uuid);
           cookie.setPath("/");
           response.addCookie(cookie);
       }
       // 如果有购物车则做添加购物车的操作
        return cartService.addProductToCart(uuid,productId,count);
    }


    // 清空购物车
    @RequestMapping("cleanCart")
    @ResponseBody
    public ResultBean cleanCart(@CookieValue(name = CartConstant.REDIS_CART,required = false)String uuid,HttpServletResponse response){

        if (uuid!=null&&!"".equals(uuid)){
            Cookie cookie=new Cookie(CartConstant.REDIS_CART,"");
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie); //浏览器中的 购物车 的 cookie被设置成了关闭浏览器就失效

            return cartService.cleanCart(uuid);// 删除Redis 中的购物车
        }
        return ResultBean.error("当前用户没有购物车");
    }

    // 查看购物车
    @RequestMapping("showCart")
    @ResponseBody
    public ResultBean showCart(@CookieValue(name = CartConstant.REDIS_CART,required = false)String uuid){

       return cartService.showCart(uuid);
    }


}
